package com.yc.d0303;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/upload.s")

@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       resp.setCharacterEncoding("utf-8");
       resp.setContentType("text/html;charset=utf-8");

        Part file = req.getPart("myfile");
        file.getContentType();
        file.getName();
        file.getSize();
        file.getSubmittedFileName();
        //file.write("f:/" +file.getSubmittedFileName());

        //resp.getWriter().println("文件上传成功！");

        ServletContext application = req.getServletContext();
        String realPath = application.getRealPath("/uploads");
        System.out.println("realPath = "+realPath);

        new File(realPath).mkdirs();

        file.write(realPath + "/"+file.getSubmittedFileName());

        String webpath = "uploads/"+file.getSubmittedFileName();
        resp.getWriter().append("文件上传成功！<br>");

        if (file.getContentType().contains("image")){
            resp.getWriter().printf("<img src ='%s' style = 'height:200px'>",webpath);
        }else {
            resp.getWriter().printf("<a href='%s' download='%s'>%s</a>"
                    ,webpath,
                    file.getSubmittedFileName(),
                    file.getSubmittedFileName());
        }


    }
}
